<template>
  <div class="my-form-overlay">
    <div class="my-form">
      <div class="form-header">
        <div class="title-up">A1111</div>
        <div class="title-down">中国国际核工业展览会</div>
      </div>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="0"
        class="form-content"
      >
        <div class="content-item">
          <div class="item-title">发票类型</div>
          <div class="item-content">
            <el-form-item prop="bill_type">
              <el-select
                v-model="formData.bill_type"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                placeholder="请选择发票类型"
                size="large"
                popper-class="invoice-select-dropdown"
                :popper-append-to-body="true"
                :disabled="props.mode === 'view'"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">开票项目</div>
          <div class="item-content">
            <el-form-item prop="bill_project">
              <el-select
                v-model="formData.bill_project"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                placeholder="请选择开票项目"
                size="large"
                popper-class="invoice-select-dropdown"
                :popper-append-to-body="true"
                :disabled="props.mode === 'view'"
              >
                <el-option
                  v-for="item in projectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">金额</div>
          <div class="item-content">
            <el-form-item prop="amount">
              <el-input
                v-model="formData.amount"
                :class="{
                  'amount-input-field': true,
                  'view-mode-input': props.mode === 'view'
                }"
                :disabled="props.mode === 'view' || props.mode === 'edit'"
                placeholder="请输入金额，如：1000.00"
                @input="handleAmountInput"
                @paste="handleAmountPaste"
                @keypress="handleAmountKeypress"
              />
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">开票信息</div>
          <div class="item-content">
            <el-form-item prop="bill_info">
              <el-input
                v-model="formData.bill_info"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                :readonly="props.mode === 'view'"
                placeholder="请输入开票信息，如：技术服务费"
              />
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">公司税号</div>
          <div class="item-content">
            <el-form-item prop="tax_number">
              <el-input
                v-model="formData.tax_number"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                :readonly="props.mode === 'view'"
                placeholder="请输入15-20位税号"
                @input="handleTaxNumberInput"
                @paste="handleTaxNumberPaste"
                @keypress="handleNumberKeypress"
              />
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">注册地址</div>
          <div class="item-content">
            <el-form-item prop="reg_addres">
              <el-input
                v-model="formData.reg_addres"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                :readonly="props.mode === 'view'"
                placeholder="请输入公司注册地址"
              />
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">注册电话</div>
          <div class="item-content">
            <el-form-item prop="reg_phone">
              <el-input
                v-model="formData.reg_phone"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                :readonly="props.mode === 'view'"
                placeholder="请输入11位手机号"
                @input="handlePhoneInput"
                @paste="handlePhonePaste"
                @keypress="handleNumberKeypress"
              />
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">开户行</div>
          <div class="item-content">
            <el-form-item prop="bank">
              <el-input
                v-model="formData.bank"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                :readonly="props.mode === 'view'"
                placeholder="请输入开户行名称"
              />
            </el-form-item>
          </div>
        </div>
        <div class="content-item">
          <div class="item-title">邮寄地址</div>
          <div class="item-content">
            <el-form-item prop="mail_address">
              <el-input
                v-model="formData.mail_address"
                :class="{ 'view-mode-input': props.mode === 'view' }"
                :readonly="props.mode === 'view'"
                placeholder="请输入发票邮寄地址"
              />
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div class="form-footer">
        <div class="button-group">
          <button class="btn btn-cancel" @click="handleCancel">取消</button>
          <button
            v-if="props.mode !== 'view'"
            class="btn btn-confirm"
            @click="handleConfirm"
          >
            {{ props.mode === "edit" ? "保存" : "申请" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineEmits, defineProps, ref, watch } from "vue";
import type { ApplyInvoiceType } from "@/api/invoice";
import { getExhibitorId } from "@/utils/getExhibitorId";

interface Props {
  mode?: "add" | "view" | "edit";
  initialData?: ApplyInvoiceType | null;
}

const props = withDefaults(defineProps<Props>(), {
  mode: "add",
  initialData: null
});

const emit = defineEmits(["cancel", "confirm"]);

const formRef = ref();

const formData = ref<ApplyInvoiceType>({
  id: 0,
  exhibitor_id: getExhibitorId() || 0,
  bill_type: "",
  bill_project: "",
  amount: "",
  bill_info: "",
  tax_number: "",
  reg_addres: "",
  reg_phone: "",
  bank: "",
  mail_address: "",
  status: 3
});

// 监听初始数据变化，更新表单数据
watch(
  () => props.initialData,
  newData => {
    if (newData) {
      formData.value = { ...newData };
    } else {
      // 重置表单数据
      formData.value = {
        id: 0,
        exhibitor_id: getExhibitorId() || 0,
        bill_type: "",
        bill_project: "",
        amount: "",
        bill_info: "",
        tax_number: "",
        reg_addres: "",
        reg_phone: "",
        bank: "",
        mail_address: "",
        status: 3
      };
    }
  },
  { immediate: true }
);

const typeOptions = [
  {
    value: "001",
    label: "增值税普通发票"
  },
  {
    value: "002",
    label: "增值税专用发票"
  }
];

const projectOptions = [
  {
    value: "001",
    label: "会议服务费"
  },
  {
    value: "002",
    label: "搭建服务费"
  }
];

// 自定义验证函数
const validateAmount = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("请输入金额"));
  } else if (!/^\d+(\.\d{1,2})?$/.test(value)) {
    callback(new Error("请输入正确的金额格式（最多两位小数）"));
  } else if (parseFloat(value) <= 0) {
    callback(new Error("金额必须大于0"));
  } else {
    callback();
  }
};

const validateTaxNumber = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("请输入公司税号"));
  } else if (!/^[0-9]{15,20}$/.test(value)) {
    callback(new Error("请输入正确的税号格式（15-20位数字）"));
  } else {
    callback();
  }
};

const validatePhone = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("请输入注册电话"));
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error("请输入正确的手机号格式"));
  } else {
    callback();
  }
};

const formRules = {
  bill_type: [{ required: true, message: "请选择发票类型", trigger: "change" }],
  bill_project: [
    { required: true, message: "请选择开票项目", trigger: "change" }
  ],
  amount: [{ required: true, validator: validateAmount, trigger: "blur" }],
  bill_info: [
    { required: true, message: "请输入开票信息", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "开票信息长度在2-100个字符之间",
      trigger: "blur"
    }
  ],
  tax_number: [
    { required: true, validator: validateTaxNumber, trigger: "blur" }
  ],
  reg_addres: [
    { required: true, message: "请输入注册地址", trigger: "blur" },
    {
      min: 5,
      max: 200,
      message: "注册地址长度在5-200个字符之间",
      trigger: "blur"
    }
  ],
  reg_phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
  bank: [
    { required: true, message: "请输入开户行", trigger: "blur" },
    {
      min: 2,
      max: 100,
      message: "开户行长度在2-100个字符之间",
      trigger: "blur"
    }
  ],
  mail_address: [
    { required: true, message: "请输入邮寄地址", trigger: "blur" },
    {
      min: 5,
      max: 200,
      message: "邮寄地址长度在5-200个字符之间",
      trigger: "blur"
    }
  ]
};

const handleCancel = () => {
  emit("cancel");
};

// 金额输入处理
const handleAmountInput = (value: string) => {
  // 只允许输入数字和小数点
  const filteredValue = value.replace(/[^\d.]/g, "");

  // 确保只有一个小数点
  const parts = filteredValue.split(".");
  if (parts.length > 2) {
    formData.value.amount = parts[0] + "." + parts.slice(1).join("");
  } else {
    formData.value.amount = filteredValue;
  }

  // 限制小数位数
  if (parts.length === 2 && parts[1].length > 2) {
    formData.value.amount = parts[0] + "." + parts[1].substring(0, 2);
  }

  // 防止以小数点开头
  if (filteredValue.startsWith(".")) {
    formData.value.amount = "0" + filteredValue;
  }
};

// 金额粘贴处理
const handleAmountPaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedText = event.clipboardData?.getData("text") || "";
  const filteredValue = pastedText.replace(/[^\d.]/g, "");

  if (filteredValue) {
    // 确保只有一个小数点
    const parts = filteredValue.split(".");
    let result = parts[0];
    if (parts.length > 1) {
      result += "." + parts.slice(1).join("").substring(0, 2);
    }

    // 防止以小数点开头
    if (result.startsWith(".")) {
      result = "0" + result;
    }

    formData.value.amount = result;
  }
};

// 金额键盘输入处理
const handleAmountKeypress = (event: KeyboardEvent) => {
  // 允许的字符：数字、小数点、退格、删除、方向键等
  const allowedKeys = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    ".",
    "Backspace",
    "Delete",
    "ArrowLeft",
    "ArrowRight",
    "Tab",
    "Enter"
  ];

  if (!allowedKeys.includes(event.key)) {
    event.preventDefault();
  }
};

// 纯数字键盘输入处理
const handleNumberKeypress = (event: KeyboardEvent) => {
  // 允许的字符：数字、退格、删除、方向键等
  const allowedKeys = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "Backspace",
    "Delete",
    "ArrowLeft",
    "ArrowRight",
    "Tab",
    "Enter"
  ];

  if (!allowedKeys.includes(event.key)) {
    event.preventDefault();
  }
};

// 电话号码输入处理
const handlePhoneInput = (value: string) => {
  // 只允许输入数字
  const filteredValue = value.replace(/\D/g, "");

  // 限制长度为11位
  if (filteredValue.length > 11) {
    formData.value.reg_phone = filteredValue.substring(0, 11);
  } else {
    formData.value.reg_phone = filteredValue;
  }
};

// 电话号码粘贴处理
const handlePhonePaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedText = event.clipboardData?.getData("text") || "";
  const filteredValue = pastedText.replace(/\D/g, "");

  if (filteredValue) {
    formData.value.reg_phone = filteredValue.substring(0, 11);
  }
};

// 税号输入处理
const handleTaxNumberInput = (value: string) => {
  // 只允许输入数字
  const filteredValue = value.replace(/\D/g, "");

  // 限制长度为20位
  if (filteredValue.length > 20) {
    formData.value.tax_number = filteredValue.substring(0, 20);
  } else {
    formData.value.tax_number = filteredValue;
  }
};

// 税号粘贴处理
const handleTaxNumberPaste = (event: ClipboardEvent) => {
  event.preventDefault();
  const pastedText = event.clipboardData?.getData("text") || "";
  const filteredValue = pastedText.replace(/\D/g, "");

  if (filteredValue) {
    formData.value.tax_number = filteredValue.substring(0, 20);
  }
};

// 通用纯数字输入处理
const handleNumberOnlyInput = (
  value: string,
  field: keyof ApplyInvoiceType
) => {
  // 只允许输入数字
  const filteredValue = value.replace(/\D/g, "");
  (formData.value as any)[field] = filteredValue;
};

const handleConfirm = () => {
  // 查看模式下不需要验证
  if (props.mode === "view") {
    return;
  }

  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      console.log("表单验证通过，提交数据:", formData.value);
      emit("confirm", formData.value);
    } else {
      console.log("表单验证失败，请检查输入");
      // 可以在这里添加更详细的错误提示
    }
  });
};
</script>

<style lang="scss" scoped>
.my-form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  padding: 20px;
  background-color: rgb(0 0 0 / 50%);
}

.my-form {
  display: flex;
  flex-direction: column;
  width: 100%;
  max-width: 1000px;
  height: auto;
  max-height: 90vh;
  overflow: hidden;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgb(0 0 0 / 15%);

  .form-header {
    padding: 20px;
    text-align: center;
    background-color: #fff;
    border-bottom: 1px solid #e0e0e0;

    .title-up {
      margin-bottom: 8px;
      font-size: 24px;
      font-weight: bold;
      color: #333;
    }

    .title-down {
      font-size: 16px;
      font-weight: bold;
      color: #666;
    }
  }

  .form-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;

    :deep(.el-form-item__label) {
      display: none;
    }

    :deep(.el-form-item) {
      padding: 0 !important;
      margin-right: 0 !important;
      margin-bottom: 0 !important;
      margin-left: 0 !important;
    }

    :deep(.el-form-item__content) {
      padding-left: 0 !important;
      margin-left: 0 !important;
    }

    :deep(.el-input__wrapper) {
      height: 40px;
      line-height: 40px;
      background-color: transparent;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      box-shadow: none;

      &:hover {
        border-color: #d9d9d9;
      }

      &.is-focus {
        background-color: transparent;
        border-color: #d9d9d9;
      }

      // 只读状态样式
      &.is-readonly {
        cursor: not-allowed;
        background-color: #f5f5f5;
        border-color: #e0e0e0;

        &:hover {
          border-color: #e0e0e0;
        }
      }

      // 禁用状态样式
      &.is-disabled {
        cursor: not-allowed;
        background-color: #f7f7f7 !important;
        border-color: #e0e0e0;

        &:hover {
          border-color: #e0e0e0;
        }

        .el-input__inner {
          background-color: #f7f7f7 !important;
          border: none !important;
          box-shadow: none !important;
        }
      }
    }

    // 专门针对金额输入框的禁用状态样式
    :deep(.amount-input-field.is-disabled .el-input__wrapper) {
      background-color: #f7f7f7 !important;
      border: 2px solid #e0e0e0 !important;

      .el-input__inner {
        color: #999 !important;
        background-color: transparent !important;
      }
    }

    // 查看模式下的输入框样式（与金额字段保持一致）
    :deep(.view-mode-input .el-input__wrapper) {
      cursor: not-allowed !important;
      background-color: #f7f7f7 !important;
      border: 2px solid #e0e0e0 !important;

      .el-input__inner {
        color: #999 !important;
        cursor: not-allowed !important;
        background-color: transparent !important;
      }
    }

    // 查看模式下的选择框样式
    :deep(.view-mode-input.el-select .el-input__wrapper) {
      cursor: not-allowed !important;
      background-color: #f7f7f7 !important;
      border: 2px solid #e0e0e0 !important;

      .el-input__inner {
        color: #999 !important;
        cursor: not-allowed !important;
        background-color: transparent !important;
      }
    }

    :deep(.el-input__inner) {
      height: 40px;
      padding: 0 16px;
      font-size: 14px;
      line-height: 40px;

      // 禁用状态下的文字样式
      &:disabled {
        color: #999;
        cursor: not-allowed;
      }
    }

    :deep(.el-select) {
      width: 100%;
    }

    :deep(.el-select .el-input__wrapper) {
      height: 40px;
      line-height: 40px;
    }

    :deep(.el-select .el-input__inner) {
      height: 40px;
      line-height: 40px;
    }

    // 禁用状态样式
    :deep(.el-select.is-disabled .el-input__wrapper) {
      cursor: not-allowed;
      background-color: #f5f5f5;
      border-color: #e0e0e0;

      &:hover {
        border-color: #e0e0e0;
      }
    }

    // 确保下拉框选项能正确显示
    :deep(.el-select-dropdown) {
      z-index: 9999 !important;
    }

    :deep(.el-select-dropdown__item) {
      height: 34px;
      padding: 0 20px;
      line-height: 34px;
    }

    .content-item {
      display: flex;
      gap: 10px;
      align-items: center;
      padding: 0 40px;
      margin-bottom: 20px;

      .item-title {
        display: flex;
        flex-shrink: 0;
        align-items: center;
        justify-content: center;
        width: 140px;
        height: 40px;
        padding: 0 16px;
        font-size: 14px;
        font-weight: 500;
        color: #333;
        text-align: center;
        background-color: #f7f8f9;
        border-radius: 4px;
      }

      .item-content {
        flex: 1;
        max-width: 750px;
        padding: 0;
        margin: 0;

        input {
          box-sizing: border-box;
          width: 100%;
          padding: 12px 16px;
          font-size: 14px;
          background-color: #f6f6f6;
          border: 1px solid #f4f4f4;
          border-radius: 6px;

          &:focus {
            outline: none;
            background-color: #fff;
            border-color: #409eff;
          }

          &::placeholder {
            color: #999;
          }
        }
      }
    }
  }

  .form-footer {
    padding: 20px;
    background-color: #fff;

    .button-group {
      display: flex;
      gap: 16px;
      justify-content: center;

      .btn {
        padding: 10px 24px;
        font-size: 14px;
        cursor: pointer;
        border: none;
        border-radius: 4px;
        transition: all 0.3s ease;

        &.btn-cancel {
          color: #666;
          background-color: #f5f5f5;
          border: 1px solid #ddd;

          &:hover {
            background-color: #e8e8e8;
            border-color: #ccc;
          }
        }

        &.btn-confirm {
          color: #fff;
          background-color: #409eff;

          &:hover {
            background-color: #337ecc;
          }
        }
      }
    }
  }
}

// 全局样式，确保下拉框能正确显示
:global(.invoice-select-dropdown) {
  z-index: 9999 !important;
}

:global(.el-select-dropdown) {
  z-index: 9999 !important;
}
</style>
